Note the version of Python. I am currently using 3.6 but it seems the tutorial is using Python 2.


In [11]:
import tensorflow as tf
sess = tf.Session()

from keras import backend as K
K.set_session(sess)

Example with MNIST


In [12]:
# this placeholder will contain our input digits, as flat vectors
img = tf.placeholder(tf.float32, shape=(None, 784))

In [13]:
from keras.layers import Dense

# Keras layers can be called on TensorFlow tensors:
x = Dense(128, activation='relu')(img)  # fully-connected layer with 128 units and ReLU activation
x = Dense(128, activation='relu')(x)
preds = Dense(10, activation='softmax')(x)  # output layer with 10 units and a softmax activation

In [14]:
labels = tf.placeholder(tf.float32, shape=(None, 10))

from keras.objectives import categorical_crossentropy
loss = tf.reduce_mean(categorical_crossentropy(labels, preds))

losses: the math and their implementation

  • trianing with tensorflow optimizer

In [15]:
from tensorflow.examples.tutorials.mnist import input_data
mnist_data = input_data.read_data_sets('MNIST_data', one_hot=True)

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

# Initialize all variables
init_op = tf.global_variables_initializer()
sess.run(init_op)

# Run training loop
with sess.as_default():
    for i in range(100):
        batch = mnist_data.train.next_batch(50)
        train_step.run(feed_dict={img: batch[0],
                                  labels: batch[1]})


Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz

Evaluating the model


In [16]:
from keras.metrics import categorical_accuracy as accuracy

In [17]:
acc_value = accuracy(labels, preds)
with sess.as_default():
    print(acc_value.eval(feed_dict={img: mnist_data.test.images, labels: mnist_data.test.labels}))


[ 1.  1.  1. ...,  1.  1.  1.]
  • odd?! I am getting the prediction not the accuracy percentage??

The optimization is done via a native TensorFlow optimizer rather than a Keras optimizer.
Keras is 5% faster but bo big noticiable difference


In [10]:



Out[10]:
<tf.Tensor 'Cast_1:0' shape=(?,) dtype=float32>

In [ ]:

Different behaviors during training and testing


In [18]:
from keras import backend as K 
print (K.learning_phase())


Tensor("keras_learning_phase:0", dtype=bool)

In [19]:
# train mode
train_step.run(feed_dict={x: batch[0], labels: batch[1], K.learning_phase(): 1})


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-19-e8cb14bb0068> in <module>()
      1 # train mode
----> 2 train_step.run(feed_dict={x: batch[0], labels: batch[1], K.learning_phase(): 1})

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in run(self, feed_dict, session)
   1586         none, the default session will be used.
   1587     """
-> 1588     _run_using_default_session(self, feed_dict, self.graph, session)
   1589 
   1590 

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in _run_using_default_session(operation, feed_dict, graph, session)
   3816     session = get_default_session()
   3817     if session is None:
-> 3818       raise ValueError("Cannot execute operation using `run()`: No default "
   3819                        "session is registered. Use `with "
   3820                        "sess.as_default():` or pass an explicit session to "

ValueError: Cannot execute operation using `run()`: No default session is registered. Use `with sess.as_default():` or pass an explicit session to `run(session=sess)`

In [22]:
from keras.layers import Dropout
from keras import backend as K

img = tf.placeholder(tf.float32, shape=(None, 784))
labels = tf.placeholder(tf.float32, shape=(None, 10))

x = Dense(128, activation='relu')(img)
x = Dropout(0.5)(x)
x = Dense(128, activation='relu')(x)
x = Dropout(0.5)(x)
preds = Dense(10, activation='softmax')(x)

loss = tf.reduce_mean(categorical_crossentropy(labels, preds))

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)
with sess.as_default():
    for i in range(100):
        batch = mnist_data.train.next_batch(50)
        train_step.run(feed_dict={img: batch[0],
                                  labels: batch[1],
                                  K.learning_phase(): 1})

acc_value = accuracy(labels, preds)
with sess.as_default():
    print (acc_value.eval(feed_dict={img: mnist_data.test.images,
                                    labels: mnist_data.test.labels,
                                    K.learning_phase(): 0}))


---------------------------------------------------------------------------
FailedPreconditionError                   Traceback (most recent call last)
/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1021     try:
-> 1022       return fn(*args)
   1023     except errors.OpError as e:

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
   1003                                  feed_dict, fetch_list, target_list,
-> 1004                                  status, run_metadata)
   1005 

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/contextlib.py in __exit__(self, type, value, traceback)
     88             try:
---> 89                 next(self.gen)
     90             except StopIteration:

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py in raise_exception_on_not_ok_status()
    468           compat.as_text(pywrap_tensorflow.TF_Message(status)),
--> 469           pywrap_tensorflow.TF_GetCode(status))
    470   finally:

FailedPreconditionError: Attempting to use uninitialized value dense_9/bias
	 [[Node: dense_9/bias/read = Identity[T=DT_FLOAT, _class=["loc:@dense_9/bias"], _device="/job:localhost/replica:0/task:0/cpu:0"](dense_9/bias)]]

During handling of the above exception, another exception occurred:

FailedPreconditionError                   Traceback (most recent call last)
<ipython-input-22-ba145c11015c> in <module>()
     19         train_step.run(feed_dict={img: batch[0],
     20                                   labels: batch[1],
---> 21                                   K.learning_phase(): 1})
     22 
     23 acc_value = accuracy(labels, preds)

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in run(self, feed_dict, session)
   1586         none, the default session will be used.
   1587     """
-> 1588     _run_using_default_session(self, feed_dict, self.graph, session)
   1589 
   1590 

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in _run_using_default_session(operation, feed_dict, graph, session)
   3830                        "the operation's graph is different from the session's "
   3831                        "graph.")
-> 3832   session.run(operation, feed_dict)
   3833 
   3834 

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    765     try:
    766       result = self._run(None, fetches, feed_dict, options_ptr,
--> 767                          run_metadata_ptr)
    768       if run_metadata:
    769         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    963     if final_fetches or final_targets:
    964       results = self._do_run(handle, final_targets, final_fetches,
--> 965                              feed_dict_string, options, run_metadata)
    966     else:
    967       results = []

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1013     if handle is None:
   1014       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
-> 1015                            target_list, options, run_metadata)
   1016     else:
   1017       return self._do_call(_prun_fn, self._session, handle, feed_dict,

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1033         except KeyError:
   1034           pass
-> 1035       raise type(e)(node_def, op, message)
   1036 
   1037   def _extend_graph(self):

FailedPreconditionError: Attempting to use uninitialized value dense_9/bias
	 [[Node: dense_9/bias/read = Identity[T=DT_FLOAT, _class=["loc:@dense_9/bias"], _device="/job:localhost/replica:0/task:0/cpu:0"](dense_9/bias)]]

Caused by op 'dense_9/bias/read', defined at:
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/ipykernel/__main__.py", line 3, in <module>
    app.launch_new_instance()
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/traitlets/config/application.py", line 658, in launch_instance
    app.start()
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/ipykernel/kernelapp.py", line 474, in start
    ioloop.IOLoop.instance().start()
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/zmq/eventloop/ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tornado/ioloop.py", line 887, in start
    handler_func(fd_obj, events)
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tornado/stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tornado/stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 276, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 228, in dispatch_shell
    handler(stream, idents, msg)
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 390, in execute_request
    user_expressions, allow_stdin)
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/ipykernel/ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/ipykernel/zmqshell.py", line 501, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2717, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2821, in run_ast_nodes
    if self.run_code(code, result):
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-22-ba145c11015c>", line 11, in <module>
    preds = Dense(10, activation='softmax')(x)
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/keras/engine/topology.py", line 528, in __call__
    self.build(input_shapes[0])
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/keras/layers/core.py", line 833, in build
    constraint=self.bias_constraint)
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/keras/engine/topology.py", line 364, in add_weight
    weight = K.variable(initializer(shape), dtype=K.floatx(), name=name)
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py", line 286, in variable
    v = tf.Variable(value, dtype=_convert_string_dtype(dtype), name=name)
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/ops/variables.py", line 226, in __init__
    expected_shape=expected_shape)
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/ops/variables.py", line 344, in _init_from_args
    self._snapshot = array_ops.identity(self._variable, name="read")
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/ops/gen_array_ops.py", line 1490, in identity
    result = _op_def_lib.apply_op("Identity", input=input, name=name)
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 763, in apply_op
    op_def=op_def)
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 2395, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1264, in __init__
    self._traceback = _extract_stack()

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value dense_9/bias
	 [[Node: dense_9/bias/read = Identity[T=DT_FLOAT, _class=["loc:@dense_9/bias"], _device="/job:localhost/replica:0/task:0/cpu:0"](dense_9/bias)]]

In [23]:
x = tf.placeholder(tf.float32, shape=(None, 20, 64))
with tf.name_scope('block1'):
    y = LSTM(32, name='mylstm')(x)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-23-dafe40b0ce78> in <module>()
      1 x = tf.placeholder(tf.float32, shape=(None, 20, 64))
      2 with tf.name_scope('block1'):
----> 3     y = LSTM(32, name='mylstm')(x)

NameError: name 'LSTM' is not defined

In [24]:
with tf.device('/gpu:0'):
    x = tf.placeholder(tf.float32, shape=(None, 20, 64))
    y = LSTM(32)(x)  # all ops / variables in the LSTM layer will live on GPU:0


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-24-1f998b0d50fe> in <module>()
      1 with tf.device('/gpu:0'):
      2     x = tf.placeholder(tf.float32, shape=(None, 20, 64))
----> 3     y = LSTM(32)(x)  # all ops / variables in the LSTM layer will live on GPU:0

NameError: name 'LSTM' is not defined

In [26]:
from keras.layers import LSTM
import tensorflow as tf

In [27]:
my_graph = tf.Graph()
with my_graph.as_default():
    x = tf.placeholder(tf.float32, shape=(None, 20, 64))
    y = LSTM(32)(x)  # all ops / variables in the LSTM layer are created as part of our graph


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/client/session.py in __init__(self, fetches, contraction_fn)
    266         self._unique_fetches.append(ops.get_default_graph().as_graph_element(
--> 267             fetch, allow_tensor=True, allow_operation=True))
    268       except TypeError as e:

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in as_graph_element(self, obj, allow_tensor, allow_operation)
   2472     with self._lock:
-> 2473       return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
   2474 

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in _as_graph_element_locked(self, obj, allow_tensor, allow_operation)
   2556       if obj.graph is not self:
-> 2557         raise ValueError("Operation %s is not an element of this graph." % obj)
   2558       return obj

ValueError: Operation name: "lstm_1/init"
op: "NoOp"
input: "^lstm_1/kernel/Assign"
input: "^lstm_1/recurrent_kernel/Assign"
input: "^lstm_1/bias/Assign"
 is not an element of this graph.

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-27-fda2d161a7a5> in <module>()
      2 with my_graph.as_default():
      3     x = tf.placeholder(tf.float32, shape=(None, 20, 64))
----> 4     y = LSTM(32)(x)  # all ops / variables in the LSTM layer are created as part of our graph

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/keras/layers/recurrent.py in __call__(self, inputs, initial_state, **kwargs)
    250             else:
    251                 kwargs['initial_state'] = initial_state
--> 252         return super(Recurrent, self).__call__(inputs, **kwargs)
    253 
    254     def call(self, inputs, mask=None, initial_state=None, training=None):

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/keras/engine/topology.py in __call__(self, inputs, **kwargs)
    526                                          '`layer.build(batch_input_shape)`')
    527                 if len(input_shapes) == 1:
--> 528                     self.build(input_shapes[0])
    529                 else:
    530                     self.build(input_shapes)

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/keras/layers/recurrent.py in build(self, input_shape)
    987                 bias_value = np.zeros((self.units * 4,))
    988                 bias_value[self.units: self.units * 2] = 1.
--> 989                 K.set_value(self.bias, bias_value)
    990         else:
    991             self.bias = None

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py in set_value(x, value)
   1968         x._assign_placeholder = assign_placeholder
   1969         x._assign_op = assign_op
-> 1970     get_session().run(assign_op, feed_dict={assign_placeholder: value})
   1971 
   1972 

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py in get_session()
    151         session = _SESSION
    152     if not _MANUAL_VAR_INIT:
--> 153         _initialize_variables()
    154     return session
    155 

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py in _initialize_variables()
    304     if uninitialized_variables:
    305         sess = get_session()
--> 306         sess.run(tf.variables_initializer(uninitialized_variables))
    307 
    308 

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    765     try:
    766       result = self._run(None, fetches, feed_dict, options_ptr,
--> 767                          run_metadata_ptr)
    768       if run_metadata:
    769         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    950 
    951     # Create a fetch handler to take care of the structure of fetches.
--> 952     fetch_handler = _FetchHandler(self._graph, fetches, feed_dict_string)
    953 
    954     # Run request and get response.

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/client/session.py in __init__(self, graph, fetches, feeds)
    406     """
    407     with graph.as_default():
--> 408       self._fetch_mapper = _FetchMapper.for_fetch(fetches)
    409     self._fetches = []
    410     self._targets = []

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/client/session.py in for_fetch(fetch)
    236         if isinstance(fetch, tensor_type):
    237           fetches, contraction_fn = fetch_fn(fetch)
--> 238           return _ElementFetchMapper(fetches, contraction_fn)
    239     # Did not find anything.
    240     raise TypeError('Fetch argument %r has invalid type %r' %

/Users/jaimealmeida/anaconda/envs/dl/lib/python3.6/site-packages/tensorflow/python/client/session.py in __init__(self, fetches, contraction_fn)
    272       except ValueError as e:
    273         raise ValueError('Fetch argument %r cannot be interpreted as a '
--> 274                          'Tensor. (%s)' % (fetch, str(e)))
    275       except KeyError as e:
    276         raise ValueError('Fetch argument %r cannot be interpreted as a '

ValueError: Fetch argument <tf.Operation 'lstm_1/init' type=NoOp> cannot be interpreted as a Tensor. (Operation name: "lstm_1/init"
op: "NoOp"
input: "^lstm_1/kernel/Assign"
input: "^lstm_1/recurrent_kernel/Assign"
input: "^lstm_1/bias/Assign"
 is not an element of this graph.)

Compatibility with variable scopes

Variable sharing should be done via calling a same Keras layer (or model) instance multiple times, NOT via TensorFlow variable scopes


In [ ]: